package model

import (
	"fmt"
	"gitee.com/liumou_site/logger"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	dnspod "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/dnspod/v20210323"
	"os"
	"strings"
)

// Update 更新记录信息
func (l *Login) Update(RecordId int) {
	// 判断IP是否一致
	if l.GetAnalyticalValue() == nil {
		if strings.EqualFold(l.IPS.Ip, l.Value) {
			logger.Info("IP地址未发生变化,无需更新")
			fmt.Println(fmt.Sprintf("%s -> %s", l.Url, l.Value))
			return
		}
	}

	// 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
	// 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
	// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
	credential := common.NewCredential(
		l.Domain.Login.Id,
		l.Domain.Login.Key,
	)
	// 实例化一个client选项，可选的，没有特殊需求可以跳过
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "dnspod.tencentcloudapi.com"
	// 实例化要请求产品的client对象,clientProfile是可选的
	client, _ := dnspod.NewClient(credential, "", cpf)

	// 实例化一个请求对象,每个接口都会对应一个request对象
	request := dnspod.NewModifyRecordRequest()

	request.Domain = common.StringPtr(l.Domain.Domain.Domain)
	request.RecordType = common.StringPtr(l.IPS.IpType)
	request.RecordLine = common.StringPtr("默认")
	request.Value = common.StringPtr(l.IPS.Ip)
	request.RecordId = common.Uint64Ptr(uint64(RecordId))
	request.SubDomain = common.StringPtr(l.Domain.Domain.Sub)
	request.Remark = common.StringPtr(l.Domain.Domain.Remark)

	// 返回的resp是一个ModifyRecordResponse的实例，与请求对象对应
	response, err := client.ModifyRecord(request)
	if _, ok := err.(*errors.TencentCloudSDKError); ok {
		fmt.Println(l.Url)

		logger.Error("无法绑定响应数据: ", err)
		logger.Debug("域名: ", l.Domain)
		logger.Debug("子域名: ", l.Domain.Domain.Sub)
		logger.Debug("解析ID：", RecordId)
		logger.Debug("解析类型: ", l.IPS.IpType)
		logger.Debug("IP地址: ", l.IPS.Ip)
		fmt.Println("")
		return
	}
	if err != nil {
		logger.Error("更新失败")
		fmt.Println(err.Error())
		fmt.Println(response.ToJsonString())
		fmt.Println(l.Url)
		os.Exit(4)
	}
	logger.Info("更新成功")
	fmt.Println(l.Url, " -> ", l.IPS.Ip)
}
